package cn.kbyue.redisdemo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ArrayUtil;
import cn.kbyue.redisdemo.common.RedisService;
import cn.kbyue.redisdemo.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author xlang
 * @date 2023/3/21 16:58
 */
@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisService redisService;

    @GetMapping("/simpleTest")
    public ResponseEntity<Product> simpleTest() {
        Product product = new Product(1200L, "中文1200");
        String key = "redis:simple:" + product.getId();
        redisService.set(key, product);
        Product cacheProduct = (Product) redisService.get(key);
        return ResponseEntity.ok(cacheProduct);
    }

    @GetMapping("hashTest")
    public ResponseEntity<Product> hashTest() {
        Product product = new Product(1211L, "中文1211");
        String key = "redis:hash:" + product.getId();
        Map<String, Object> value = BeanUtil.beanToMap(product);
        redisService.hSetAll(key, value);
        Map<Object, Object> cacheValue = redisService.hGetAll(key);
        Product cacheProduct = BeanUtil.mapToBean(cacheValue, Product.class, true, CopyOptions.create().ignoreNullValue());
        return ResponseEntity.ok(cacheProduct);
    }

    @GetMapping("setTest")
    public ResponseEntity<Set<Object>> setTest() {
        Product product = new Product(1203L, "中文1203");
        Product product2 = new Product(12022L, "中文12022");
        Product product3 = new Product(12022L, "中文12022");
        List<Product> productList = Arrays.asList(product, product2, product3);
        String key = "redis:set:all";
        redisService.sAdd(key, (Object[]) ArrayUtil.toArray(productList, Product.class));
        redisService.sRemove(key, productList.get(0));
        Set<Object> cachedBrandList = redisService.sMembers(key);
        return ResponseEntity.ok(cachedBrandList);
    }

    @GetMapping("listTest")
    public ResponseEntity<List<Object>> listTest() {
        Product product = new Product(1204L, "中文1204");
        Product product2 = new Product(1206L, "中文1206");
        Product product3 = new Product(1206L, "中文1206");
        List<Product> productList = Arrays.asList(product, product2, product3);
        String key = "redis:list:all";
        redisService.lPushAll(key, (Object[]) ArrayUtil.toArray(productList, Product.class));
        redisService.lRemove(key, 1, productList.get(0));
        List<Object> cachedBrandList = redisService.lRange(key, 0, 3);
        return ResponseEntity.ok(cachedBrandList);
    }

}
